//
//  PresentAnimator.m
//  Elephant
//
//  Created by enghou on 2018/5/30.
//  Copyright © 2018年 xyxorigation. All rights reserved.
//

#import "PresentAnimator.h"
#import "XIBView.h"
@implementation PresentAnimator

- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext{
    return self.duration;
}
// This method can only  be a nop if the transition is interactive and not a percentDriven interactive transition.
- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext{
    UIViewController *toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    /** 原控制器 */
    UIViewController *fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    
    UIView *toView = nil;
    UIView *fromView = nil;
    
    if ([transitionContext respondsToSelector:@selector(viewForKey:)]) {
        fromView = [transitionContext viewForKey:UITransitionContextFromViewKey];
        toView = [transitionContext viewForKey:UITransitionContextToViewKey];
    } else {
        fromView = fromViewController.view;
        toView = toViewController.view;
    }
    /** containView */
    UIView *containView = [transitionContext containerView];
    [containView addSubview:toView];
    [containView bringSubviewToFront:toView];
    if ([toView.subviews count] > 0) {
        UIView *subView = toView.subviews[0];
        if ([subView isKindOfClass:[XIBView class]]) {
            subView.transform = CGAffineTransformMakeScale(0, 0);
            subView.center = toView.center;
            [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
                subView.transform = CGAffineTransformMakeScale(1, 1);
            } completion:^(BOOL finished) {
                BOOL wasCancelled = [transitionContext transitionWasCancelled];
                [transitionContext completeTransition:!wasCancelled];
            }];
            return;
        }
    }
    BOOL wasCancelled = [transitionContext transitionWasCancelled];
    [transitionContext completeTransition:!wasCancelled];
}

@end
